package com.example.esc.controller;


import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.example.esc.utils.AliPayUtils;
import com.example.esc.vo.Result;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.util.UUID;

@RestController
@RequestMapping("/pay")
public class AlipayController {
    /**
     * 进行支付宝的支付
     */
    @RequestMapping("/alipay")
    public void aliPay(HttpServletResponse resp, HttpServletRequest req) throws UnsupportedEncodingException {
        //订单号,测试随机生成->订单的支付金额
        String oid = UUID.randomUUID().toString();
        //测试价格写死,实际开发中根据订单id获取到订单金额
        //String price ="2";

        //调用支付宝API
        AlipayClient alipayClient = AliPayUtils.getAlipayClient();
        //构造一个支付请求
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        //异步回调,用于接收支付宝服务器的回调请求
        request.setNotifyUrl("http://xxxxxx这里可以放一个外网访问主机ip/pay/result");
        //同步回调,重定向url,跳转到百度...实际开发中根据需求跳转到指定的页面.
        request.setReturnUrl("http://127.0.0.1/user_home_order.html");

        //封装请求体
        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = new String(req.getParameter("WIDout_trade_no").getBytes("ISO-8859-1"),"UTF-8");
        //付款金额，必填
        String total_amount = new String(req.getParameter("WIDtotal_amount").getBytes("ISO-8859-1"),"UTF-8");
        //订单名称，必填
        String subject = req.getParameter("WIDsubject");
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", out_trade_no);
        bizContent.put("total_amount", total_amount);
        bizContent.put("subject", subject);
        bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");

        request.setBizContent(bizContent.toString());
        AlipayTradePagePayResponse response = null;
        try {
            response = alipayClient.pageExecute(request);
            if(response.isSuccess()){
                System.out.println("调用成功!!OK");
                //拿到支付宝服务器响应的响应体
                String body = response.getBody();
                //将响应体,写入浏览器
                resp.setContentType("text/html;charset=utf-8");
                resp.getWriter().print(body);
                resp.getWriter().close();
            } else {
                System.out.println("支付宝调用失败...");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("/result")
    public void payResult(){
        System.out.println("接收到支付宝的回调请求!!!");
    }
}


